package com.collectplus.express;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.Selection;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.collectplus.express.model.ReceiverBean;
import com.umeng.analytics.MobclickAgent;

import java.util.List;

import droid.frame.App;
import droid.frame.activity.base.FrameBaseActivity;
import droid.frame.activity.title.TitleMgr;
import droid.frame.activity.title.TitleRes;
import droid.frame.ui.dialog.AppLoading;
import droid.frame.utils.android.ImmUtils;
import droid.frame.utils.android.Log;
import droid.frame.utils.android.VibratorMgr;
import droid.frame.utils.http.HttpLoader;
import droid.frame.utils.lang.JsonParser;
import droid.frame.utils.lang.Str;

/**
 * 因为涉及上存在较大缺陷，后期该类由 {@link BaseActivity2}代替
 *
 * @author coffee 2013年12月19日下午7:08:30
 */
// @Deprecated
public abstract class BaseActivity extends FrameBaseActivity {

    private TitleMgr titleMgr;

    @SuppressLint("ResourceAsColor")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setStatusBarColor(R.color.app_status);
        super.onCreate(savedInstanceState);
    }

    private ProgressBar mProgressBar;
    private TextView mEmptyView;

    @Override
    protected void findViewById() {
        titleMgr = new TitleMgr(getContext());
        titleMgr.initTitle();
        try {
            int loadingId = getResources().getIdentifier("loading_progressBar", "id", getPackageName());
            getResources().getResourceName(loadingId);
            mProgressBar = (ProgressBar) findViewById(loadingId);
            if (mProgressBar != null) {
                mProgressBar.setVisibility(View.GONE);
            }
            int emptyId = getResources().getIdentifier("empty_text", "id", getPackageName());
            mEmptyView = (TextView) findViewById(emptyId);
            if (mEmptyView != null) {
                ((ViewGroup) mEmptyView.getParent()).setVisibility(View.GONE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        Thread.setDefaultUncaughtExceptionHandler(((ExpressApplication) getApplication()).getUncaughtExceptionHandler());
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    protected View.OnClickListener mBackClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    };

    /**
     * 显示通用Title<br>
     * 调用该方法时需要确保子类成功调用了 {@link #findViewById()}
     */
    public void setCommonTitle(String titleText) {
        setCommonTitle(titleText, null);
    }

    public void setCommonTitle(String titleText, TitleRes rightTitle) {
        titleMgr.setTitle(new TitleRes[]{new TitleRes(R.drawable.title_back_selector, new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        }), new TitleRes(0, titleText, null), rightTitle});
    }

    public void setTitle(TitleRes... reses) {
        titleMgr.setTitle(reses);
    }

    /**
     * 设置右侧按钮
     *
     * @param res
     */
    protected void setTitleRight(TitleRes res) {
        titleMgr.handleTitle(titleMgr.getTitleRight(), res, 2);
    }

    /**
     * 设置组件可见性<br>
     * 注意该方法需要在setTitle之后调用, 否则无效
     *
     * @param position   0-左 1-中 2-右
     * @param visibility {@link View#VISIBLE View#GONE}
     */
    protected void setTitleVisibility(int position, int visibility) {
        if (position == 0) {
            titleMgr.getTitleLeft().setVisibility(visibility);
        } else if (position == 1) {
            titleMgr.getTitleMiddle().setVisibility(visibility);
        } else if (position == 2) {
            titleMgr.getTitleRight().setVisibility(visibility);
        }
    }

    public void setTitleBackground(int backgroundRes) {
        View layout = findViewById(R.id.app_title_layout);
        layout.setBackgroundResource(backgroundRes);
    }

    public void setTitleBackgroundColor(int backgroundColor) {
        View layout = findViewById(R.id.app_title_layout);
        layout.setBackgroundColor(backgroundColor);
    }

    // 隐藏键盘输入法
    public final static int MSG_IMM_HIDE = 1000;
    public final static int MSG_IMM_SHOW = 1000 + 1;

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_IMM_HIDE:
                ImmUtils.hide(getContext());
                break;
        }
        return false;
    }

    public void startActivity(Class<?> classActivity) {
        Intent intent = new Intent();
        intent.setClass(getContext(), classActivity);
        startActivity(intent);
    }

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode) {
        super.startActivityForResult(intent, requestCode);
    }

    @SuppressLint("RestrictedApi")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        FragmentManager fm = getSupportFragmentManager();
        int index = requestCode >> 16;
        if (index != 0) {
            index--;
            if (fm.getFragments() == null || index < 0
                    || index >= fm.getFragments().size()) {
                Log.d("BaseActivity2", "Activity result fragment index out of range: 0x" + Integer.toHexString(requestCode));
                return;
            }
            Fragment frag = fm.getFragments().get(index);
            if (frag == null) {
                Log.d("BaseActivity2", "Activity result no fragment exists for index: 0x"
                        + Integer.toHexString(requestCode));
            } else {
                handleResult(frag, requestCode, resultCode, data);
            }
            return;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 递归调用，对所有子Fragement生效
     *
     * @param frag
     * @param requestCode
     * @param resultCode
     * @param data
     */
    private void handleResult(Fragment frag, int requestCode, int resultCode,
                              Intent data) {
        frag.onActivityResult(requestCode & 0xffff, resultCode, data);
        @SuppressLint("RestrictedApi")
        List<Fragment> frags = frag.getChildFragmentManager().getFragments();
        if (frags != null) {
            for (Fragment f : frags) {
                if (f != null)
                    handleResult(f, requestCode, resultCode, data);
            }
        }
    }

    // ******************************************************************************************

    public boolean isEmpty(Object str) {
        if (str == null || str.toString().trim().length() == 0) {
            return true;
        } else {
            return false;
        }
    }

    public boolean isNotEmpty(Object str) {
        return !isEmpty(str);
    }

    public void showLoadingBar() {
        if (mProgressBar != null) {
            mProgressBar.setVisibility(View.VISIBLE);
        }
    }

    public void cancelLoadingBar() {
        if (mProgressBar != null) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mProgressBar.setVisibility(View.GONE);
                }
            });
        }
    }

    /**
     * 该方法主要考虑到一个界面里多个EmptyView
     *
     * @param emptyText
     */
    protected void setEmptyTextView(TextView emptyText) {
        this.mEmptyView = emptyText;
    }

    public void setEmptyView(ViewGroup viewGroup, String emptyText) {
        if (mEmptyView == null) {
            return;
        }
        //
        if (viewGroup instanceof ListView || viewGroup instanceof GridView) {
            AbsListView mAbsListView = (AbsListView) viewGroup;
            if (mAbsListView == null || mAbsListView.getAdapter() == null || mAbsListView.getAdapter().getCount() == 0) {
                ((View) mEmptyView.getParent()).setVisibility(View.VISIBLE);
                if (isEmpty(emptyText) == false) {
                    mEmptyView.setText(emptyText);
                }
            } else {
                ((View) mEmptyView.getParent()).setVisibility(View.GONE);
            }
        }
        // else if (viewGroup instanceof XListView) {
        // XListView xListView = (XListView) viewGroup;
        // // XListView含有Footer
        // if (xListView == null || xListView.getListView().getAdapter() == null || xListView.getListView().getAdapter().getCount() <= 1) {
        // ((View) mEmptyView.getParent()).setVisibility(View.VISIBLE);
        // if (isEmpty(emptyText) == false) {
        // mEmptyView.setText(emptyText);
        // }
        // } else {
        // ((View) mEmptyView.getParent()).setVisibility(View.GONE);
        // }
        // }
        // else if (viewGroup instanceof droid.frame.view.pull3refresh.XListView) {
        // droid.frame.view.pull3refresh.XListView xListView = (droid.frame.view.pull3refresh.XListView) viewGroup;
        // // XListView含有Footer
        // if (xListView == null || xListView.getRefreshableView().getAdapter() == null || xListView.getRefreshableView().getAdapter().getCount() <= 2) {
        // ((View) mEmptyView.getParent()).setVisibility(View.VISIBLE);
        // if (isEmpty(emptyText) == false) {
        // mEmptyView.setText(emptyText);
        // }
        // } else {
        // ((View) mEmptyView.getParent()).setVisibility(View.GONE);
        // }
        // }
    }

    /**
     * ********* 加载框相关 **********
     */

    private AppLoading loading;

    public void showLoadingDialog(final String dialogMessage) {
        getContext().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (loading != null && loading.isShowing()) {
                    loading.setMessage(dialogMessage);
                    return;
                } else {
                    loading = new AppLoading(getContext());
                    loading.setMessage(dialogMessage);
                    loading.show();
                }
            }
        });
    }

    protected void cancelLoadingDialog() {
        getContext().runOnUiThread(new Runnable() {
            public void run() {
                if (loading != null) {
                    loading.dismiss();
                }
            }
        });
    }

    public void showToastError(String jsonStr, String attr) {
        final Object err = JsonParser.get(jsonStr, attr);
        App.getHandler().post(new Runnable() {
            @Override
            public void run() {
                final Toast toast = Toast.makeText(getContext(), "", Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.TOP, 0, 200);
                // TextView v = (TextView) toast.getView().findViewById(android.R.id.message);
                // v.setBackgroundColor(color)
                // v.setTextColor(Color.RED);
                if (err == null || "".equals(err)) {
                    toast.setText("操作失败");
                } else {
                    toast.setText(err.toString());
                }
                toast.show();
            }
        });
    }

    /**
     * 移动光标到最后
     */
    public void setCursorToLast(EditText editText) {
        // 光标移动到最后
        Editable editable = editText.getEditableText();
        Selection.setSelection(editable, editable.length());
    }

    /**
     * 振动
     */
    public void vibrate() {
        VibratorMgr.vibrate(500);
    }

    public void setButtonEnableStyle(Button button, boolean enable) {
        int bottom = button.getPaddingBottom();
        int top = button.getPaddingTop();
        int right = button.getPaddingRight();
        int left = button.getPaddingLeft();
        if (enable) {
            button.setBackgroundResource(R.drawable.app_button_selector);
            button.setTextColor(getResources().getColorStateList(R.color.app_buttoncolor_selector));
        } else {
            button.setBackgroundResource(R.drawable.app_button_bg_disable);
            button.setTextColor(getResources().getColor(R.color.app_font_2));
        }
        button.setPadding(left, top, right, bottom);
    }

    /**
     * 加载图片
     *
     * @param receiver
     * @param image
     */
    public void loadImage(ReceiverBean receiver, ImageView image) {
        String url = receiver.getGoodsImage();
        if (Str.isEmpty(url)) {
            url = receiver.getParcelImgUrl();
        }
        HttpLoader.getInstance().loadImage(url, image, getContext());
    }

    // 跳转到主页面
    public void goMainFragmentActivity() {
        getContext().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent();
                intent.setClass(getContext(), MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                finish();// 关闭当前Activity
            }
        });
    }
}
